﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;
    import LRTM = Sustainalytics.LRTM;

    // Portfolio List controller
    export class PortfolioOverviewController {

        // portfolio filter
        public portfolioCompanyFilter: PortfolioCompanyFilterDto;
        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of portfolios
        public portfolioCompanyList: PortfolioCompanyDto[];
        // current portfolio
        public portfolio: PortfolioDto;

        // total number of portfolios
        public portfolioCompanyCount: number;
        private accountId: string;
        private userId: string;
        private scopeDestroyed: boolean;
        public isMyPortfolio: boolean;
        public isRenamingPortfolioName: boolean;
        public newNamePortfolio: string;
        public portfolioExcel: any;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private $routeParams: ng.route.IRouteParamsService,
            private PortfolioService: PortfolioService,
            private PortfolioCompanyService: PortfolioCompanyService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            var ctx = this;
            ctx.$routeParams = $routeParams;

            $scope['portfolioOverview'] = ctx;

            ctx.scopeDestroyed = false;

            ctx.portfolioCompanyFilter = new PortfolioCompanyFilterDto();
            ctx.portfolioCompanyFilter.portfolioId = ctx.$routeParams['id'];

            ctx.orderByCol = "CompanyNameLowercase";
            ctx.orderByAsc = true;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();

            ctx.getPortfolioById();
        }

        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });
        }

        // search for portfolios when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.searchPortfolioCompany();
            });
        }

        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.searchPortfolioCompany();
        }

        // search list of portfolios
        public searchPortfolioCompany(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            // get portfolio items
            var promiseGet: ng.IPromise<PortfolioCompanyDto[]> = ctx.PortfolioCompanyService.getPortfolioCompanies(ctx.portfolioCompanyFilter, skip, take, [ctx.orderByCol], ctx.orderByAsc, ctx.accountId, ctx.userId);

            var portfolioCompanyListTemp: PortfolioCompanyDto[];

            //on success list portfolios
            promiseGet.then(function (lst) {
                portfolioCompanyListTemp = lst;
            });

            //get portfolios count
            var promiseCount: ng.IPromise<number> = ctx.PortfolioCompanyService.getPortfolioCompaniesCount(ctx.portfolioCompanyFilter, ctx.accountId, ctx.userId);

            var portfolioCompanyCountTemp: number;

            //on success 
            promiseCount.then(function (count) {
                portfolioCompanyCountTemp = count;
            });

            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([promiseGet, promiseCount]);

            promiseAll
                .then(function () {
                    ctx.portfolioCompanyList = portfolioCompanyListTemp;
                    ctx.portfolioCompanyCount = portfolioCompanyCountTemp['portfolioCompanyCount'];
                    pager.setTotalItemsCount(portfolioCompanyCountTemp['portfolioCompanyCount']);
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseAll;
        }

        public getPortfolioById(): ng.IPromise<PortfolioDto> {
            var ctx = this;
            ctx.$rootScope['loading'] = true;

            // get news by id
            var promiseGet: ng.IPromise<PortfolioDto> = ctx.PortfolioService.getPortfolioById(ctx.$routeParams['id'], ctx.accountId, ctx.userId);

            //on success
            promiseGet
                .then(function (data) {
                    ctx.portfolio = data;
                    ctx.isRenamingPortfolioName = false;
                    ctx.newNamePortfolio = data["name"];
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        public deletePortfolioCompany(id): ng.IPromise<{}> {
            var ctx = this;

            if (confirm("Are you sure you want to remove the selected security from current portfolio?")) {

                var promiseDelete = ctx.PortfolioCompanyService.deletePortfolioCompany(id, ctx.$routeParams['id']);

                promiseDelete.then(function () {
                    // repopulate list
                    ctx.searchPortfolioCompany();
                    ctx.portfolio.dateModified = new Date();
                    ctx.portfolio.companyCount--;
                });
                return promiseDelete;
            }
        }

        public setShared(item: PortfolioDto): ng.IPromise<{}> {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = 2;

            var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

            promiseUpdate.then(function () {
                item.sharingStatus = 2;
            });

            return promiseUpdate;
        }

        public setPrivate(item: PortfolioDto): ng.IPromise<{}> {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = 1;

            var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

            promiseUpdate.then(function () {
                item.sharingStatus = 1;
            });

            return promiseUpdate;
        }

        public changeIsRenaming() {
            var ctx = this;
            if (ctx.portfolio.isMyPortfolio) {
                ctx.isRenamingPortfolioName = !ctx.isRenamingPortfolioName;
                ctx.newNamePortfolio = ctx.portfolio.name;
            }
        }

        public renamePortfolio() {
            var ctx = this;

            var portfolioRename = new PortfolioRenameDto();
            portfolioRename.id = ctx.portfolio.id;
            portfolioRename.newPortfolioName = ctx.newNamePortfolio;
            portfolioRename.oldPortfolioName = ctx.portfolio.name;

            var promiseRename = ctx.PortfolioService.renamePortfolio(portfolioRename);

            promiseRename
                .then(function () {
                    ctx.portfolio.name = ctx.newNamePortfolio;
                    ctx.portfolio.dateModified = new Date();
                    ctx.isRenamingPortfolioName = false;
                })
                ['catch'](function () {
                });
        }

        public addTaskExportPortfolio(): void {
            var ctx = this;
            var portfolioExcel;

            var data = {
                id: ctx.$routeParams['id'], 
                accountId : ctx.accountId, 
                userId: ctx.userId,
                name: ctx.portfolio.name
            }

            var promise = ctx.LongRunningTaskManagerService.runTask('Portfolio_'+ ctx.portfolio.name + "_" + moment().format("DDMMYYYY"), angular.toJson(data), 4, true, null);
        }
    }

    // register controller with Portfolio Angular module
    angular.module('Sustainalytics.Portfolio').controller('PortfolioOverviewController', function ($rootScope: ng.IScope, $scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, $routeParams: ng.route.IRouteParamsService, PortfolioService, PortfolioCompanyService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, LongRunningTaskManagerService) {
        var ctrl = new Sustainalytics.Portfolio.PortfolioOverviewController($rootScope, $scope, $q, $location, $routeParams, PortfolioService, PortfolioCompanyService, notificationFactory, staticObjects, LongRunningTaskManagerService);
        return ctrl;
    });
} 